﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LightCAD.Runtime;
using LightCAD.WinForm;

namespace LightCAD.UI
{
    public static class UIUtils
    {
        /// <summary>
        /// 触发命令
        /// </summary>
        /// <param name="uiCmdName">UI发出的命令名, 如"tbi_Line"</param>
        /// <exception cref="Exception"></exception>
        public static void ExecuteCommand(string uiCmdName)
        {
            int splitPos = uiCmdName.IndexOf("_");
            if (splitPos < 0)
            {
                throw new Exception($"Command {uiCmdName} format is error, should be xxx_[CmdName].");
            }

            // 提取到命令名，如"Line"
            string cmdString = uiCmdName.Substring(splitPos + 1).Replace("_", " ");

            const int delay = 10;
            AsyncUtils.Execute(
                () =>
                    {
                        App.Current.ActiveWindow.Invoke(() => { CommandCenter.Instance.Execute(cmdString.ToUpper()); }); // 在UI线程上执行
                    },
                delay);
        }

        internal static MainUI? GetMainUI(Control control)
        {
            var owner = GetParent<Form>(control).Owner;
            if (owner == null) return null;
            var mainWin = owner as MainUIWindow;
            if(mainWin == null) return null;
            return mainWin.mainUI;
        }

        internal static T GetParent<T>(Control control) where T : Control
        {
            while (control != null)
            {
                if (control.Parent is T)
                    return (T)control.Parent;
                control = control.Parent;
            }
            return default(T);
        }
    }
}